package web.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import entity.Extract;
import entity.MyFile;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import service.FileService;

import java.io.*;
import java.util.Date;

public class FileUpLoadAction extends ActionSupport implements ModelDriven<MyFile> {

    private FileService fs;

    private MyFile myFile = new MyFile();

    public String upLoad() throws IOException {

        //已接收到myFile对象
        File file = myFile.getFiles();
        Extract extract = (Extract) ServletActionContext.getRequest().getSession().getAttribute("extract");
        //对myFile的属性进行封装
        myFile.setExtract(extract);
        myFile.setFile_size(file.length());
        myFile.setUpload_date(new Date());
        myFile.setDownload_count(0);
        myFile.setIconBySuffix(myFile.getSuffix());
        myFile.setFile_path("C:\\Users\\zer\\Desktop\\智慧云打印\\上传文件测试\\"+myFile.getExtract().getFile_signal());//设置上传文件保存到服务器的路径(文件夹)
        //文件上传成功,将文件对象存入数据库
            fs.save(myFile);
        File directory = new File(myFile.getFile_path());
        // 查找文件夹,没有就创建!
        if (!directory.exists()){
            //文件夹不存在
            directory.mkdir();
        }
        //对文件进行上传
        //1、创建磁盘文件项工厂
        //作用：设置缓存文件的大小  设置临时文件存储的位置
        DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024,directory);
        //2、创建文件上传的核心类
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置上传文件的名称的编码
        upload.setHeaderEncoding("UTF-8");

        InputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = new FileOutputStream(myFile.getFile_path()+'/'+myFile.getFilesFileName());
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();

        return NONE;
    }

    @Override
    public MyFile getModel() {

        return myFile;
    }

    public void setFs(FileService fs) {
        this.fs = fs;
    }
}
